<template>
    <div>
        <header-test :name="`${typeMap[type]}地址`" />
        <div class="address_form">
            <van-address-edit
                :area-list="areaList"
                :address-info="addressInfo"
                :show-postal="false"
                show-delete
                show-set-default
                show-search-result
                :search-result="searchResult"
                :area-columns-placeholder="['请选择','请选择','请选择']"
                @save = "onSave"
                @delete="onDelete"
                @change-default="onChangeDetail"
            />
        </div>
        
    </div>
</template>

<script>
import { onMounted,reactive,toRefs } from 'vue';
import HeaderTest from '@/components/HeaderTest.vue';
import {
    addAddress,
    EditAddress,
    DeleteAddress,
    getAddressDetail,
} from "@/service/address.js"
import { tdist } from '@/common/utils';
import { useRoute,useRouter } from 'vue-router';
import { Toast } from 'vant';
export default {
    components:{ HeaderTest },
    setup() {
        const typeMap = {
            add: "新增",
            edit:"修改",
        };
        const route = useRoute();
        const router = useRouter();
        const state = reactive({
            areaList: {},
            addressInfo: {},
            addressId:"",
            type:"",
            from:"",
            searchResult:[],
        });

        onMounted(async()=>{
            let _province_list = {};
            let _city_list = {};
            let _county_list = {};
            tdist.getLev1().forEach((p) => {
                _province_list[p.id] = p.text;
                tdist.getLev2(p.id).forEach((c)=>{
                    _city_list[c.id] = c.text;
                    tdist.getLev3(c.id).forEach((q)=>(_county_list[q.id]=q.text));
                });
            });
            state.areaList.province_list = _province_list;
            state.areaList.city_list = _city_list;
            state.areaList.county_list = _county_list;

            const { addressId,type,from } = route.query;
            state.addressId = addressId;
            state.type = type;
            state.from = from || "";
            if(type=="edit") {
                const { data:addressDetail } = await getAddressDetail(addressId);
                let _areaCode = "";
                const province = tdist.getLev1();
                Object.entries(state.areaList.county_list).forEach(([id,text])=>{
                    if(text==addressDetail.regionName){
                        const provinceIndex=province.findIndex(
                            (item)=>item.id.substr(0,2) == id.substr(0,2)
                        );

                        const cityItem = Object.entries(state.areaList.city_list).filter(
                            ([cityId,cityName]) => cityId.substr(0,4) == id.substr(0,4)
                        )[0];

                        if(
                            province[provinceIndex].text == addressDetail.proviceName &&
                            cityItem[1] == addressDetail.cityName
                        ) {
                            _areaCode = id;
                        }
                    }
                });

                state.addressInfo = {
                    id: addressDetail.addressId,
                    name :addressDetail.userName,
                    tel: addressDetail.userPhone,
                    province: addressDetail.provinceName,
                    city:addressDetail.cityName,
                    county: addressDetail.regionName,
                    addressDetail:addressDetail.detailAddress,
                    areaCode:_areaCode,
                    isDefault:!!addressDetail.defaultFlag,
                } ;
            }
        });

        const onSave = async(values) => {
            const {
                name:userName,
                tel:userPhone,
                province:provinceName,
                city:cityName,
                county :regionName,
                addressDetail:detailAddress,
                isDefault,
            } = values;

            const params = {
                userName,
                userPhone,
                provinceName,
                cityName,
                regionName,
                detailAddress,
                defaultFlag:isDefault?1:0,
            };
            let res;
            if(state.type === "edit") {
                res = await EditAddress({...params,addressId:state.addressId});
                if (res.resultCode === 200){

                }
            }else{
                res=await addAddress(params);
            }
            if(res.resultCode===200){
                Toast.success(`${typeMap[state.type]}成功`);
                router.push("/address");
            }
        };

        const onDelete = () =>{};
        const onChangeDetail = (val) =>{
            if(val){
                state.searchResult = [
                    {
                        name:"黄龙万科中心",
                        address:"杭州市西湖区",
                    },
                ];
            }else{
                state.searchResult = [];
            }
        };
        return {
            ...toRefs(state),
            typeMap,
            onSave,
            onDelete,
            onChangeDetail,
        };
    },
};

</script>

<style lang="less" scoped>
.address_form {
    margin-top:3rem;
}
</style>